package com.sdyc.utils.file;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 动态配置属性文件
 *
 * Created by Rayn on 2015/10/3.
 */
public class DynamicFileUtils implements Runnable
{

    /**
     * 属性文件
     */
    private static File file;

    private static String s = "";

    /**
     * 文件名称
     */
    private String filename;

    /**
     * 文件的最后修改时间
     */
    private static long lastModify = System.currentTimeMillis();

    /**
     * 乐观锁
     */
    private final static ReentrantReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();

    private final static Lock readLock = READ_WRITE_LOCK.readLock();

    private final static Lock writeLock = READ_WRITE_LOCK.writeLock();


    /**
     * 是否已经初始化
     */
    private static boolean init = false;

    /**
     * 初始化后内部的扫描线程
     */
    private Thread scanThread = null;



    static {
        writeLock.lock();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if(loader == null) {
                loader = DynamicFileUtils.class.getClassLoader();
            }

            URL resource = loader.getResource("");
            file = new File(resource.getFile(), "test.json");

//            jsString = FileUtils.readFileToString(file);
            s = readFileContext( file );

            //log.info("初始化文件成功.");

            lastModify = System.currentTimeMillis();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    private DynamicFileUtils () {
        if(!init && scanThread == null) {
            scanThread = new Thread(this);
            init = true;
        }
    }

    private DynamicFileUtils (String filename) {
        if(!init && scanThread == null) {
            scanThread = new Thread(this);
//            scanThread.start();
            init = true;
            this.filename = filename;
        }
    }



    @Override
    public void run ()
    {
        while (true)
        {
            if(file.lastModified() > lastModify)
            {

//            log.info( "文件模板发生改变，将要重新加载." );
                writeLock.lock();
                try
                {
//                jsString = FileUtils.readFileToString( file );
                    String context = readFileContext( file );

                    System.out.println( context );

                    lastModify = System.currentTimeMillis();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } finally
                {
                    writeLock.unlock();
                }
            }
            try
            {
                scanThread.wait( 2 * 1000L );
            } catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 文件内容读取
     */
    public static String readFileContext(File file) throws IOException {


        try{

            Reader reader = new FileReader( file );

            char [] temp = new char[1024];
            int len = 0;
            while(reader.read(temp, len, 1024 ) > 0){
                s += new String( temp );
            }
            System.out.println(s);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return s;
    }

    public final static String getTrackerJS(boolean changed, String filename) {
        if(changed) {
            if(!init && null != filename) {
                new DynamicFileUtils(filename);
            } else if(!init) {
                new DynamicFileUtils();
            }
            readLock.lock();
            try {
                return s;
            } finally {
                readLock.unlock();
            }
        } else {
            return s;
        }
    }

    public static void main ( String[] args )
    {
        DynamicFileUtils dynamicFileUtils = new DynamicFileUtils("test.json");
        dynamicFileUtils.run();

//        System.out.println(getTrackerJS(false, "test.json"));
    }
}
